package com.example.calculator1;

import static java.lang.Math.sqrt;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

public class MainActivity2 extends AppCompatActivity {

    public static final String TAG = "tag";
    public static final int update = 0x1;
    @SuppressLint("StaticFieldLeak")
    static TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        textView = findViewById(R.id.textView2);
        begin();
    }

    @SuppressLint("HandlerLeak")
    private static final Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            if (msg.what == update) {
                textView.setText(String.valueOf(msg.arg1));
                textView.setText(String.valueOf(msg.obj));
            }
        }
    };
    public void begin() {
        new Thread(new Runnable() {
            int j;
            @Override
            public void run() {
                for(int i = 2; i < 20; i++){
                    Message msg = new Message();
                    msg.what = update;
                    msg.arg1 = i;

                    int root = (int)sqrt(i);
                    for(j = 2; j <= root; j++){
                        if(i%j == 0)
                            break;
                    }
                    if(j > root)
                        msg.obj = i + "是素数";
                    else
                        msg.obj = i + "不是素数";

                    handler.sendMessage(msg);
                    try{
                        Thread.sleep(1000);
                    } catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
                startActivity(new Intent(MainActivity2.this, MainActivity.class));
                finish();
            }
        }).start();
    }
    @Override
    protected void onDestroy(){
        super.onDestroy();
        Log.v(TAG, "onDestroy");
    }

}